package com.ran.servlets;

import com.ran.po.Book;
import com.ran.service.BookService;
import com.ran.service.IBookServcie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import com.google.gson.Gson;

@WebServlet("/list_book")
public class ListBook extends HttpServlet {

    private IBookServcie bookServcie;
    @Override
    public void init() throws ServletException {
        bookServcie = new BookService();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置 CORS 头，允许所有来源的请求
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 如果需要支持特定的 HTTP 方法（如 POST, PUT, DELETE），可以添加以下头
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        List<Book> bookList = bookServcie.getAll();

        response.setContentType("application/json;charset=UTF-8");
        Gson gson = new Gson();
        String json = gson.toJson(bookList);
        response.getWriter().write(json);


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }




}